package com.lyandwc.lw_bbs.security.common;

import com.lyandwc.lw_bbs.entity.User;
import com.lyandwc.lw_bbs.security.entity.Role;
import com.lyandwc.lw_bbs.security.entity.UserAuthDetails;
import com.lyandwc.lw_bbs.security.service.RoleService;
import com.lyandwc.lw_bbs.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserAuthDetailsService implements UserDetailsService {

    private UserService userService;
    private RoleService roleService;

    public UserAuthDetailsService(UserService userService, RoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findUserByName(username);
        if (user != null) {
            UserAuthDetails userAuthDetails = new UserAuthDetails();
            BeanUtils.copyProperties(user, userAuthDetails);

            Set<GrantedAuthority> authorities = new HashSet<>();
            List<Role> roleList = roleService.findRoleByUserId(userAuthDetails.getId());
            roleList.forEach(role -> authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName())));

            userAuthDetails.setAuthorities(authorities);

            return userAuthDetails;
        }
        return null;
    }
}
